const Service = require('egg').Service
class OrderService extends Service {
  // 新增
  async add({ user_id }, transaction) {
    let params = {
      user_id
    }
    let res = await this.ctx.model.Order.create(params, { transaction })
    return res
  }
  // 新增子项
  async addItem({ order_id, goods }, transaction) {
    let task = []
    for (let item of goods) {
      let params = {
        order_id,
        num: item.goods_num,
        goods_id: item.id,
        goods_name: item.name,
        goods_price: item.price,
        goods_img: item.photo
      }
      task.push(this.ctx.model.OrderItem.create(params, { transaction }))
    }
    const res = await Promise.all(task)
    return res
  }
  // 获取收入
  async getIncome({ user_id }) {
    let goods_res = await this.ctx.model.Goods.findAll({
      where: { user_id }
    })
    // console.log('订单数：', goods_res)
    let goods_ids = goods_res.map((item) => item.dataValues.id)
    console.log('商品ids', goods_ids)
    let order_item_res = await this.ctx.model.OrderItem.findAll({
      where: { goods_id: { [this.app.Sequelize.Op.or]: goods_ids } }
    })
    let all_income = 0
    order_item_res.forEach((item) => {
      all_income += Number(item.goods_price)
    })
    let goods_count = 0
    order_item_res.forEach((item) => {
      goods_count += Number(item.num)
    })
    console.log('1111，', all_income)
    return {
      all_income: all_income,
      goods_count: goods_count
    }
  }
}
module.exports = OrderService
